<?php

	session_start();

	// check for login
	if(!isset($_SESSION['atbat']) && !isset($_COOKIE['remember_atbat'])) {

		// no login, move to index page
		header("Location: http://localhost/atbat/html/");

	}

	// connect to db
	require_once '../db/db.php';

	// get user id
	$sql = "SELECT user_id FROM users WHERE MD5(username) IN ('";
	$sql .= ((isset($_SESSION['atbat'])) ? $_SESSION['atbat'] : '') . "', '";
	$sql .= ((isset($_COOKIE['remember_atbat'])) ? $_COOKIE['remember_atbat'] : '') . "')";
		
	$id = $db->query($sql)->fetchAll();
	$user_id = $id[0]['user_id'];

	// get roster info based on url hash
	if(isset($_GET['id']) && $_GET['id'] != '') {

		$sql = "SELECT * FROM rosters WHERE roster_id = " . $_GET['id'];
		$roster = $db->query($sql)->fetch(PDO::FETCH_ASSOC);

	}else{ // return to main roster page

		header("Location: http://localhost/atbat/html//rosters");

	}
	
	// process request
	if(isset($_POST['editRoster'])) {
	
		$error = false;
	
		if(isset($_POST['team_id']) && $_POST['team_id'] != '') {
		
			$team_id = filter_var($_POST['team_id'], FILTER_SANITIZE_STRING);
			
		}else{
		
			$message[] = '<p class="error">Please choose a team for this roster.</p>';
			$error = true;
			
		}
		
		if(isset($_POST['nickname']) && $_POST['nickname'] != '') {
		
			$nickname = filter_var($_POST['nickname'], FILTER_SANITIZE_STRING);
			
		}else{
		
			$message[] = '<p class="error">Please name this roster.</p>';
			$error = true;
		
		}
		
		if(isset($_POST['roster_id']) && $_POST['roster_id'] != '') {
		
			$roster = filter_var($_POST['roster_id'], FILTER_SANITIZE_NUMBER_INT);
		
		}else{
		
			$message[] = '<p class="error">Cannot determine roster id.</p>';
			$error = true;
		
		}
		
		if($error == false) {
		
			$sql = "UPDATE rosters SET team_id = " . $team_id . ", user_id = " . $user_id . ", ";
			$sql = "nickname = '" . $nickname . "' WHERE roster_id = " . $roster;
			
			if($db->exec($sql) == 1) {
				
				// show success message
				$message[] = '<p rel="' . $roster . '" title="' . $nickname .'" class="success">Successfully updated your roster.</p>';
			
			}else{
			
				$message[] = '<p class="error">Could not update roster.</p>';
				$error = true;
			
			}
		
		}
	
	}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="http://localhost/atbat/html/" />
	<meta charset="utf-8">
	<title>AtBat :: Rosters - Edit Roster</title>
	<meta name="description" content="">
	<meta name="author" content="Sean Mullin, http://parametercontraption.com">
	<!--  Mobile Viewport Fix j.mp/mobileviewport & davidbcalhoun.com/2010/viewport-metatag -->
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
	<link rel="shortcut icon" href="images/design/favicon.ico">
	<link rel="apple-touch-icon" href="images/design/apple-touch-icon.png">
	<link rel="stylesheet" href="css/screen.css">
	<!-- For the less-enabled mobile browsers like Opera Mini --><link rel="stylesheet" media="all" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css">
    <script src="js/modernizr-1.5.min.js"></script>
</head>
<body>
	<?php require_once 'include/header.html'; ?>
    <section id="content">
    	<h1>Edit This Roster</h1>
        <p>Use the form below to edit your roster.</p>
        <form method="post" action="create-roster">
        	<fieldset id="create_roster">
            	<legend>Roster Details</legend>
                <?php if(isset($message)) foreach($message as $m) print $m; ?>
                <p>
                	<label for="team">Select a Team:</label>
                    <select name="team" id="team" required>
                    	<option value="0">Choose One</option>
                    	<?php
							
							foreach($db->query("SELECT team_id, city, name FROM teams WHERE team_id = " . $roster['team_id']) as $t) {
							
								print '<option value="' . $t['team_id'] . '" selected>' . $t['city'] . ' ' . $t['name'] . '</option>';
							
							}
							
							foreach($db->query("SELECT team_id, city, name FROM teams WHERE user_id IN (0, " . $user_id . ") AND team_id != " . $roster['team_id']) as $t) {
							
								print '<option value="' . $t['team_id'] . '">' . $t['city'] . ' ' . $t['name'] . '</option>';
							
							}
						
						?>
                    	<option value="">Create a New Team</option>
                    </select>
                </p>
                <p><label for="nickname">Roster Nickname:</label><input type="text" name="nickname" id="nickname" value="<?php echo $roster['nickname']; ?>" required/></p>
                <input type="submit" name="editRoster" id="editRoster" value="Edit Roster" />
                <input type="reset" name="cancel" id="cancel" value="Cancel" />
                <input type="hidden" name="roster_id" id="roster_id" value="<?php echo $roster['roster_id']; ?>" />
            </fieldset>
        </form>
    </section>
    <?php require_once 'include/footer.html'; ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
	<script>
    	$(document).ready(function() {
			// listen for change event on team input
			$("#team").change(function() {
				if($("#team").val() == '') {
					$("#dialogTeam").dialog("open");
				}
			});
			
			// new team dialog
			$("#dialogTeam").dialog({
				autoOpen: false,
				width: 648,
				modal: true,
				draggable: false,
				resizable: false,
				buttons: {
					"Create Team": function() {
						$.post(
							"create-team.php",
							{
								team_city: $("#team_city").val(),
								team_name: $("#team_name").val(),
								division: $("#division").val(),
								league: $("#league").val(),
								url: $("#url").val(),
								createTeam: $("#createTeam").val()
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialogTeam").prepend(data);
								if($(data).hasClass('success')) {
									// set value of team select input
									var select_id = $(data).attr("rel");
									var select_title = $(data).attr("title");
									$("#team").append('<option value="' + select_id + '" selected>' + select_title + '</option>');
									// enable roster select
									$("#roster").attr("disabled", "");
									// close window after 5 seconds on success
									setTimeout(function() { $("#dialogTeam").dialog("close"); }, 2500);
								}
							}
						);
					},
					Cancel: function() { $(this).dialog("close"); }
				}
			});
		});
    </script>
    <fieldset id="dialogTeam" title="Create a New Team">
    	<p><label for="team_city">Team City:</label><input type="text" name="team_city" id="team_city" required /></p>
        <p><label for="team_name">Team Name:</label><input type="text" name="team_name" id="team_name" required /></p>
        <p>
            <label for="division">Division:</label>
            <select name="division" id="division">
                <?php
                
                    $sql = "SHOW COLUMNS FROM teams LIKE 'division'";
                    $divs = $db->query($sql)->fetchAll();
                    $div = $divs[0]['Type'];
                                                
                    $regex = "/'(.*?)'/";
                    preg_match_all($regex, $div, $enum_array);
                    $enum_fields = $enum_array[1];
                    
                    foreach($enum_fields as $type) print '<option value="' . $type . '">' . $type . '</option>';
                
                ?>
            </select>    
        </p>
        <p>
            <label for="league">League:</label>
            <select name="league" id="league">
                <?php
                
                    $sql = "SHOW COLUMNS FROM teams LIKE 'league'";
                    $divs = $db->query($sql)->fetchAll();
                    $div = $divs[0]['Type'];
                                                
                    $regex = "/'(.*?)'/";
                    preg_match_all($regex, $div, $enum_array);
                    $enum_fields = $enum_array[1];
                    
                    foreach($enum_fields as $type) print '<option value="' . $type . '">' . $type . '</option>';
                    
                ?>
            </select>
        </p>
        <p><label for="url">Team URL:</label><input type="url" name="url" id="url" placeholder="http://www.example.com" /></p>
        <input type="hidden" name="createTeam" value="1" id="createTeam" />
    </fieldset>
</body>
</html>